
#封装三级商品分类
from collections import OrderedDict

from apps.goods.models import GoodsChannel


def get_categories():
    # 1.获取第一层级
    # 1.1获取商品频道表37个数据
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')
    categories = OrderedDict()
    for channel in channels:
        group_id = channel.group_id
        if group_id not in categories:
            categories[group_id] = {"channels": [], "sub_cats": []}

        cat1 = channel.category
        cat1.url = channel.url
        categories[group_id]["channels"].append(cat1)
        # 2.获取第二层级
        for cat2 in cat1.subs.all():
            cat2.sub_cats = []
            # 3.获取第三层级
            for cat3 in cat2.subs.all():
                cat2.sub_cats.append(cat3)
            categories[group_id]["sub_cats"].append(cat2)
    return categories